package com.cyx.fruit.controller;

import com.cyx.fruit.pojo.Fruit;
import com.cyx.fruit.service.FruitService;
import com.cyx.fruit.util.StringUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

public class FruitController{

    FruitService service;//属性 -- 成员变量

    private String add(String fname,Integer price,Integer fcount) throws IOException {
        Fruit fruit = new Fruit();
        fruit.setFname(fname);
        fruit.setPrice(price);
        fruit.setFcount(fcount);
        fruit.setRemark("不错");
        service.addFruit(fruit);
        return "redirect:fruit.do";    //请求重定向
    }
    private String del(String fid) throws IOException {
        service.delFruit(Integer.valueOf(fid));
        return "redirect:fruit.do";
    }
    private String edit(Integer fid,HttpServletRequest req) throws IOException {
        if(fid != null){
            Fruit fruits = service.getFruitByFid(fid);
            req.getSession().setAttribute("fruits",fruits);
            System.out.println(fruits);
            return "edit";
        }else{
            return "add";
        }
    }
    private String index(String likeSearch,String keyword,Integer pageNumber,HttpServletRequest req) throws IOException {
        HttpSession session = req.getSession();

        if(pageNumber == null){
            pageNumber = 1;
        }
        if (StringUtil.isEmpty(keyword)) {
            keyword = "";
        }

        /**
         * operate == null
         * operate != null
         */
        //对查询方式做判断
        if(StringUtil.isNotEmpty(likeSearch) & "search".equals(likeSearch)){

            session.setAttribute("keyword",keyword);   //将查询关键字保存在会话域
            System.out.println("cx"+keyword);
            pageNumber = 1;//默认从首页开始
        }else{
            //没有点击查询按钮
            Object objKeyword = session.getAttribute("keyword");
            /**
             * 点上一页，下一页
             */
            if(objKeyword!= null){
                //带着模糊查询关键字的翻页
                keyword = (String) objKeyword;
            }
        }




        List<Fruit> fruitlist = service.getFruitList(keyword,pageNumber);
        session = req.getSession();
        //将数据列表存入session域中
        req.getSession().setAttribute("pageNumber",pageNumber);
        req.getSession().setAttribute("fruitlist",fruitlist);

        Integer page = service.getPage(keyword);
        session.setAttribute("pageCount",page);

        return "index";
    }
    private String update(Integer fid,String fname,Integer price,Integer fcount,String remark,HttpServletRequest req) throws IOException {

        Fruit fruit = new Fruit(fid,fname,price,fcount,remark);
        service.updateFruit(fruit);
        //请求重定向
        return "redirect:fruit.do";
    }
}